package com.six.controller;

import com.six.result.Result;
import com.six.result.ResultUtils;
import com.six.utils.TencentCOS;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Api(tags = "上传接口")
@RestController
@RequestMapping("/upload")
@Slf4j
public class UploadController {
    @ApiOperation(value = "上传图片接口",notes = "上传图片接口",httpMethod = "POST")
    @PostMapping("/image")
    public Result uploadImage(@RequestParam MultipartFile image) throws IOException {

        //获取原来的名字
        String originalFilename = image.getOriginalFilename();
        //获取后缀
        String ext=originalFilename.substring(originalFilename.lastIndexOf("."));
        //生成新的名字
        String newName= UUID.randomUUID().toString().replace("-","")+ext;
        log.info("生成的文件名为:{}",newName);

        //创建一个临时的File对象
        File file=File.createTempFile("image-",newName);

        //把图片转存到临时的File对象
        image.transferTo(file);

        //把临时的File对象发送给腾讯云进行存储
        String fileName = TencentCOS.uploadfile(file, "guagua");

        log.info("上传到腾讯云服务器:{}",fileName);

        //删除临时文件
        if(file.exists()){
            file.delete();
        }

        //返回图片的路径
        return ResultUtils.buildSuccess("https://yyb-1309743310.cos.ap-chengdu.myqcloud.com/guagua/"+fileName);

    }
}
